/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-04-22
 * Time:15:23
 */

/**
 * BM16删除有序链表中重复的元素-山
 */

public class deleteDuplicatesⅡ {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode pre = dummy;
        ListNode cur = head;

        while (cur != null) {
            boolean duplicated = false;
            while (cur.next != null && cur.val == cur.next.val) {
                duplicated = true;
                cur = cur.next;
            }

            if (duplicated) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }

            cur = cur.next;
        }

        return dummy.next;
    }
}
